use std::{time::SystemTime};
use ecdsa::Signature;
use p256::ecdsa::signature::Signer;
use p256::NistP256;
use url::Url;
use crate::api::get_jwt::JWT_INSTANCE; // 假设这个实例是正确的
use base64::{engine::general_purpose::STANDARD, Engine as _}; // 使用标准Base64编码

// 获得Windows时间戳，单位为100纳秒
fn get_windows_timestamp() -> u64 {
    let now = SystemTime::now();
    let duration_since_unix_epoch = now.duration_since(std::time::UNIX_EPOCH).unwrap();
    let unix_epoch_seconds = duration_since_unix_epoch.as_secs();
    
    // 转换为100纳秒单位
    let windows_epoch_offset_seconds: u64 = 11644473600;
    (unix_epoch_seconds + windows_epoch_offset_seconds) * 10_000_000
}

/**
 * @description: 获得签名(base64)
 * @param {String} url 请求地址
 * @param {String} authorization_token 获取的sisu_token
 * @param {String} payload 请求体
 */
pub fn get_signature(url: &str, authorization_token: &str, payload: &str) -> String {
    let timestamp = get_windows_timestamp();
    let url_parsed = Url::parse(url).unwrap();
    let path_and_query = url_parsed.path();

    let mut buf = Vec::new();

    // 写入版本和保留字节
    buf.extend_from_slice(&1u32.to_be_bytes()); // version (4字节)
    buf.extend_from_slice(&0u8.to_be_bytes()); // reserved (1字节)
    buf.extend_from_slice(&timestamp.to_be_bytes()); // timestamp (8字节)
    buf.extend_from_slice(&0u8.to_be_bytes()); // reserved (1字节)
    
    // 写入方法 (POST)
    buf.extend_from_slice(b"POST");
    buf.extend_from_slice(&0u8.to_be_bytes());
    
    // 写入路径
    buf.extend_from_slice(path_and_query.as_bytes());
    buf.extend_from_slice(&0u8.to_be_bytes());
    
    // 写入授权令牌
    buf.extend_from_slice(authorization_token.as_bytes());
    buf.extend_from_slice(&0u8.to_be_bytes());
    
    // 写入payload
    buf.extend_from_slice(payload.as_bytes());
    buf.extend_from_slice(&0u8.to_be_bytes());

    // 使用私钥签名
    // 这里确保 jwt_instance.signing_key 是 p256::ecdsa::SigningKey
    let signature: Signature<NistP256> = JWT_INSTANCE.get().unwrap().signing_key.sign(&buf);
    let signature_bytes = signature.to_bytes();
    
    // 构建最终头部
    let mut header = Vec::new();
    
    // 写入头部版本
    header.extend_from_slice(&1u32.to_be_bytes());
    
    // 写入时间戳
    header.extend_from_slice(&timestamp.to_be_bytes());
    
    // 写入签名
    header.extend_from_slice(&signature_bytes);

    // 使用标准Base64编码
    STANDARD.encode(header)
}